<script lang="ts" setup>
import type { VxeGridProps } from '#/adapter/vxe-table';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { getcarList, updatecar, deletecar } from '#/api/core/car';
import type { VbenFormProps } from '@vben/common-ui';
import { ElButton, ElMessage, ElMessageBox } from 'element-plus';
import { useVbenForm } from '#/adapter/form';
import { useVbenDrawer } from '@vben/common-ui';
import { ref } from 'vue';

const [Drawer, drawerApi] = useVbenDrawer({
  title: '编辑车辆',
  footer: false,
});

interface RowType {
  category: string;
  color: string;
  id: string;
  price: string;
  productName: string;
  releaseDate: string;
}

/**
 * 获取示例表格数据
 */
async function getExampleTableApi(params: {
  page: any;
  size: any;
  carplate?: any;
}) {
  console.log(params);
  return new Promise<{ items: any; total: number }>(async (resolve) => {
    const { page, size, carplate } = params;
    const items = await getcarList({
      page,
      size,
      carplate,
    });

    resolve({
      total: items.data.total,
      items: items.data.list,
    });
  });
}

const gridOptions: VxeGridProps<RowType> = {
  checkboxConfig: {
    highlight: true,
    labelField: 'name',
  },
  pagerConfig: {
    pageSizes: [2, 20, 50],
  },
  columns: [
    { title: '序号', type: 'seq', width: 50 },
    { align: 'left', title: '车牌号', field: 'carPlate', width: 100 },
    { field: 'carOwner', title: '车主' },

    { field: 'carName', title: '车辆名称' },
    { field: 'carType', title: '车辆品牌' },
    {
      field: 'createdAt',
      formatter: 'formatDateTime',
      title: '创建时间',
      sortable: true,
    },
    {
      field: 'updatedAt',
      formatter: 'formatDateTime',
      title: '更新时间',
      sortable: true,
    },
    {
      field: 'action',
      fixed: 'right',
      slots: { default: 'action' },
      title: '操作',
      width: 120,
    },
  ],
  exportConfig: {},
  // height: 'auto', // 如果设置为 auto，则必须确保存在父节点且不允许存在相邻元素，否则会出现高度闪动问题
  keepSource: true,
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues) => {
        return await getExampleTableApi({
          page: page.currentPage,
          size: page.pageSize,

          ...formValues,
        });
      },
    },
  },
  toolbarConfig: {
    custom: true,
    export: true,
    // import: true,
    refresh: true,
    zoom: true,
  },
};

const formOptions: VbenFormProps = {
  // 默认展开
  collapsed: false,
  schema: [
    {
      component: 'Input',
      componentProps: {
        placeholder: '输入车牌',
      },
      defaultValue: '',
      fieldName: 'carplate',
      label: '车牌',
    },
  ],
  // 控制表单是否显示折叠按钮
  showCollapseButton: false,
  submitButtonOptions: {
    content: '查询',
  },
  // 按下回车时是否提交表单
  submitOnEnter: false,
};

const [Grid, gridApi] = useVbenVxeGrid({
  gridOptions,
  formOptions,
});
const car = ref({
  id: 0,
  CarOwner: '',
  CarPlate: '',
  carName: '',
  CarType: '',
});
const open = (row: {
  id: number;
  carOwner: string;
  carPlate: string;
  carName: string;
  carType: string;
}) => {
  car.value.id = row.id;
  car.value.CarOwner = row.carOwner;
  car.value.CarPlate = row.carPlate;
  car.value.carName = row.carName;
  car.value.CarType = row.carType;
  formApi.setValues(car.value);
  drawerApi.open();
};
const onSubmitcar = (values: Record<string, any>) => {
  let obj = {
    id: car.value.id,
    ...values,
  };
  updatecar(obj).then(() => {
    gridApi.query();
    ElMessage.success('修改成功');
    drawerApi.close();
  });
};
const [Formcar, formApi] = useVbenForm({
  // 所有表单项共用，可单独在表单内覆盖
  commonConfig: {
    // 所有表单项
    componentProps: {
      class: 'w-full',
    },
  },
  // 提交函数
  handleSubmit: onSubmitcar,
  // 垂直布局，label和input在不同行，值为vertical
  // 水平布局，label和input在同一行
  layout: 'horizontal',
  schema: [
    {
      // 组件需要在 #/adapter.ts内注册，并加上类型
      component: 'VbenInput',
      // 对应组件的参数
      componentProps: {
        placeholder: '请输入车主',
      },
      // 字段名
      fieldName: 'CarOwner',
      disabled: false,
      // 界面显示的label
      label: '车主姓名',
    },
    {
      // 组件需要在 #/adapter.ts内注册，并加上类型
      component: 'VbenInput',
      // 对应组件的参数
      componentProps: {
        placeholder: '请输入车牌',
      },
      rules: 'required',
      // 字段名
      fieldName: 'CarPlate',
      // 界面显示的label
      label: '车牌号',
    },
    {
      // 组件需要在 #/adapter.ts内注册，并加上类型
      component: 'VbenInput',
      // 对应组件的参数
      componentProps: {
        placeholder: '请输入车型',
      },
      rules: 'required',
      // 字段名
      fieldName: 'carName',
      // 界面显示的label
      label: '车型',
    },
    {
      // 组件需要在 #/adapter.ts内注册，并加上类型
      component: 'VbenInput',
      // 对应组件的参数
      componentProps: {
        placeholder: '请输入车辆品牌',
      },
      rules: 'required',
      // 字段名
      fieldName: 'CarType',
      // 界面显示的label
      label: '车辆品牌',
    },
  ],
  wrapperClass: 'grid-cols-1',
});
const del = (data: { id: number }) => {
  ElMessageBox.confirm('此操作将永久删除该车辆, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    deletecar(data.id).then(() => {
      ElMessage.success('删除成功');
      gridApi.query();
    });
  });
};
</script>

<template>
  <div class="vp-raw w-full">
    <Grid>
      <template #action="{ row }">
        <el-button link type="primary" @click="open(row)">编辑</el-button>
        <el-button link type="danger" @click="del(row)">删除</el-button>
      </template>
    </Grid>
    <Drawer class="w-[800px]" ref="drawer"><Formcar /> </Drawer>
  </div>
</template>
